<?php
/**
 * This file is part of Notadd.
 *
 * @author        Hollydan <2642956839@qq.com>
 * @copyright (c) 2017, notadd.com
 * @datetime      17-11-20 下午6:02
 */

namespace Notadd\Seckill\GraphQL\Queries;


use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\Type;
use Notadd\Foundation\GraphQL\Abstracts\Query;
use Notadd\Foundation\Validation\Rule;
use Notadd\Seckill\Models\Product;
use Notadd\Seckill\Models\Seckill;

class ProductListQuery extends Query
{
    /**
     * @return array
     */
    public function args()
    {
        return [
            'order' => [
                'name' => 'order',
                'rules' => Rule::in([
                    'asc',
                    'desc',
                ]),
                'type' => Type::string(),
                'defaultValue' => 'desc',
            ],
            'page' => [
                'name' => 'page',
                'rules' => Rule::numeric(),
                'type' => Type::int(),
            ],
            'paginate' => [
                'name' => 'paginate',
                'rules' => Rule::numeric(),
                'type' => Type::int(),
                'defaultValue' => 20,
            ],
            'seckillId' => [
                'name' => 'skill_id',
                'rules' => Rule::numeric(),
                'type' => Type::int(),
                'description' => '活动 ID',
            ],
        ];
    }

    /**
     * @param $root
     * @param $args
     *
     * @return mixed
     */
    public function resolve($root, $args)
    {

        if (isset($args['seckillId'])) {
            $products = Seckill::query()->find($args['seckillId'])->products()->orderBy('created_at', $args['order'])->paginate($args['paginate']);
        } else {
            $products = Product::query()->orderBy('created_at', $args['order'])->paginate($args['paginate']);
        }
        return json_encode([
            'code' => 200,
            'data' => $products->items(),
            'pagination' => [
                'total'         => $products->total(),
                'per_page'      => $products->perPage(),
                'current_page'  => $products->currentPage(),
                'last_page'     => $products->lastPage(),
                'next_page_url' => $products->nextPageUrl(),
                'prev_page_url' => $products->previousPageUrl(),
                'from'          => $products->firstItem(),
                'to'            => $products->lastItem(),
            ],
            'message' => '获取商品列表成功！',
        ]);
    }

    /**
     * @return \GraphQL\Type\Definition\ListOfType
     */
    public function type(): ListOfType
    {
        return Type::listOf($this->graphql->type('Product'));
    }
}